package com.lishe.lishe.lishe.module.mall.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lishe.lishe.R;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerviewBaseAdapter;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.bean.SpaceItemDecoration;
import com.lishe.lishe.lishe.module.mall.adapter.ClassificationMallAdapter;
import com.lishe.lishe.lishe.module.mall.bean.category.CategoryGoods;
import com.lishe.lishe.lishe.module.mall.presenter.ClassificationPresenter;
import com.lishe.lishe.lishe.utils.Utils;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.lishe.lishe.retrofit.bean.DataPageItemBody;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;

/**
 * Created by Bin
 * 查看更多
 */

public class LoadMoreActivity extends BaseActivity implements View.OnClickListener {

    public static void jump(Activity activity, String cate_id, String title) {
        Intent intent = new Intent(activity, LoadMoreActivity.class);
        intent.putExtra("cate_id", cate_id);
        intent.putExtra("title", title);
        activity.startActivity(intent);
    }

    private RecyclerView mMallRecycle;
    private RelativeLayout mErrorLayout;
    private View mEmptyLayout;
    private View mConditionEmptyLayout;
    private SmartRefreshLayout mSmartRefreshLayout;

    private ArrayList<CategoryGoods> mList = new ArrayList<>();
    private ClassificationMallAdapter mAdapter;
    private int mPage = 1;
    private int mPageSize = 20;
    private String mTitle;
    private String mCateId;
    private int mTotalPage;//总页数
    private String mBind = "desc", mPrice = null, mSold = null, mShop = null, mPriceRange = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loadmore);
        mTitle = getIntent().getStringExtra("title");
        mCateId = getIntent().getStringExtra("cate_id");
        initView();
        setListener();
        setAdapter();
        setSmartRefreshLayout();
    }

    private void initView() {
        //title
        TextView title = findViewById(R.id.title_text_title);
        title.setText(mTitle);

        mMallRecycle = findViewById(R.id.mall_list);
        mErrorLayout = findViewById(R.id.error);
        mSmartRefreshLayout = findViewById(R.id.refreshlayout);
        //empty
        mEmptyLayout = findViewById(R.id.empty_layout);
        //筛选 empty
        mConditionEmptyLayout = findViewById(R.id.condition_empty_layout);

        mMallRecycle.addItemDecoration(new SpaceItemDecoration(0, Utils.dip2px(LoadMoreActivity.this, 10), 0, Utils.dip2px(LoadMoreActivity.this, 10)));
        mMallRecycle.setLayoutManager(new GridLayoutManager(LoadMoreActivity.this, 2));
    }

    private void setListener() {
        mErrorLayout.setOnClickListener(this);
        findViewById(R.id.govisit).setOnClickListener(this);
        findViewById(R.id.title_left_button).setOnClickListener(this);
    }

    private void setAdapter() {
        mAdapter = new ClassificationMallAdapter(LoadMoreActivity.this, mList);
        mMallRecycle.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new RecyclerviewBaseAdapter.ItemListener.ItemClickListener() {
            @Override
            public void OnClickListener(RecyclerView.Adapter adapter, View view, int position) {
                GoodsDetailActivity.jump(LoadMoreActivity.this, mList.get(position).getItem_id());
            }
        });
    }

    private void setSmartRefreshLayout() {
        mSmartRefreshLayout.autoRefresh(0, 1, 0.62f);
        mSmartRefreshLayout.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）
        mSmartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mPage = 1;
                getMoreItem();
                mSmartRefreshLayout.setLoadmoreFinished(false);//将会再次触发加载更多事件
                if (!mSmartRefreshLayout.isEnableLoadmore()) {
                    mSmartRefreshLayout.setEnableLoadmore(true);
                }
            }
        });

        mSmartRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //未加载完，可以LoadMore
                if (mPage <= mTotalPage) {
                    mSmartRefreshLayout.setLoadmoreFinished(false);//将会再次触发加载更多事件
                    getMoreItem();
                } else {
                    mSmartRefreshLayout.finishLoadmore();
                    mSmartRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.govisit:
                //TODO
                finish();
                break;
            case R.id.title_left_button:
                finish();
                break;
            case R.id.error:
                mSmartRefreshLayout.autoRefresh(0, 1, 0.62f);
                break;
        }
    }

    public void getMoreItem() {
        if (mEmptyLayout.getVisibility() == View.VISIBLE) {
            mEmptyLayout.setVisibility(View.GONE);
        }
        if (mErrorLayout.getVisibility() == View.VISIBLE) {
            mErrorLayout.setVisibility(View.GONE);
        }
        try {
            ClassificationPresenter.getInstance().getMoreItems(mCateId, mBind, mPrice, mSold, mShop, mPriceRange, mPage, mPageSize, listener);
        } catch (Exception e) {
            e.printStackTrace();
            toast(getString(R.string.data_parse_fail));
        }
    }

    private DataResponseListener<DataPageItemBody<CategoryGoods>> listener = new DataResponseListener<DataPageItemBody<CategoryGoods>>() {
        @Override
        public void onSuccess(DataPageItemBody<CategoryGoods> dataResponse) {
            if (mPage == 1) {
                mSmartRefreshLayout.finishRefresh(0, true);
                mList.clear();
                mAdapter.notifyDataSetChanged();
            } else {
                mSmartRefreshLayout.finishLoadmore(0, true);
            }

            mPage++;
            if (dataResponse != null) {
                mTotalPage = dataResponse.getTotalPage();
                mList.addAll(dataResponse.getItems());
            }

            if (mList.size() > 0) {
                mEmptyLayout.setVisibility(View.GONE);
                mConditionEmptyLayout.setVisibility(View.GONE);
                mAdapter.notifyDataSetChanged();
            } else {
                showEmpty();
                mSmartRefreshLayout.setEnableLoadmore(false);
            }
        }

        @Override
        public void onFail(String failMessage) {
            //网络差是刷新界面显示1秒钟后消失
            mSmartRefreshLayout.finishRefresh(1000, false);
            mSmartRefreshLayout.finishLoadmore(1000, false);

            if (mList.size() == 0) {
                mSmartRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
                showEmpty();
            }
            toast("没有该类型的商品");
        }

        @Override
        public void onError(Throwable e) {
            //网络差是刷新界面显示1秒钟后消失
            mSmartRefreshLayout.finishRefresh(1000, false);
            mSmartRefreshLayout.finishLoadmore(1000, false);

            if (mList.size() == 0) {
                mSmartRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
                showError();
            }

            Log.e("TAG", "e = " + e.toString());
            toast(R.string.network_or_server_exception);
        }
    };

    private void showError() {
        if (mList.size() > 0) {
            mList.clear();
            mAdapter.notifyDataSetChanged();
        }
        mErrorLayout.setVisibility(View.VISIBLE);
    }

    private void showEmpty() {
        if (mList.size() > 0) {
            mList.clear();
            mAdapter.notifyDataSetChanged();
        }
    }

}
